package com.test.pudamoney.util_pudamoney.http_pudamoney;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.test.pudamoney.util_pudamoney.StringUtil_pudamoney;
import com.test.pudamoney.util_pudamoney.ThreadUtil_pudamoney;
import com.test.pudamoney.util_pudamoney.analytics_pudamoney.util_pudamoney.AnalyticsUtil_pudamoney;
import com.test.pudamoney.util_pudamoney.helper_pudamoney.UserInfoHelper_pudamoney;
import com.test.pudamoney.activity_fragment_pudamoney.base_pudamoney.BaseApplication_pudamoney;
import com.test.pudamoney.constant_pudamoney.Constant_pudamoney;
import com.test.pudamoney.constant_pudamoney.Url_pudamoney;
import com.test.pudamoney.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpManager_pudamoney {
    
    public static String Upload_Info_Url="";


    private HttpManager_pudamoney() {
        if (BuildConfig.DEBUG) {
            mHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }
        mClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(mHttpLoggingInterceptor)
                .addInterceptor(new ReqInterceptor_pudamoney())
                .callTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
    }

    private static class Inner {
        private static final HttpManager_pudamoney instance = new HttpManager_pudamoney();
    }

    public static HttpManager_pudamoney getInstance() {
        return Inner.instance;
    }

    private static OkHttpClient mClient;

    private static final HttpLoggingInterceptor mHttpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLogger_pudamoney());

    //请求响应回调
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            HttpPresenter_pudamoney.getInstance().showToastOnUiThread("Request Fail");
            ThreadUtil_pudamoney.getInstance().runOnUiThread(() -> HttpPresenter_pudamoney.getInstance().progressBarDialogDismiss());
            Log.e("Http Response", "Request Fail");
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String body = Objects.requireNonNull(response.body()).string();
            ThreadUtil_pudamoney.getInstance().runOnUiThread(() -> HttpPresenter_pudamoney.getInstance().progressBarDialogDismiss());
            try {
                String word = StringUtil_pudamoney.getUrlSuffix(response.request().url().toString());
                handleResponse(word, new JSONObject(body));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    //处理响应
    private void handleResponse(String lastWord, JSONObject responseJson) {
        ThreadUtil_pudamoney.getInstance().runOnUiThread(() -> HttpPresenter_pudamoney.getInstance().notifyActivityHandleResponse(lastWord, responseJson));
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson() {
        return getRequestJson(new JSONObject());
    }

    private JSONObject getRequestJson(JSONObject jsonObject) {
        try {
            jsonObject.put("isLimitAdTrackingEnabled", AnalyticsUtil_pudamoney.INSTANCE.getAdEnabled() + "");
            jsonObject.put("aduid", AnalyticsUtil_pudamoney.INSTANCE.getAdId());
            jsonObject.put("aduidPath", AnalyticsUtil_pudamoney.INSTANCE.getAndroidId());
            jsonObject.put("version", Constant_pudamoney.APP_VERSION.trim());
            jsonObject.put("token", UserInfoHelper_pudamoney.getInstance().getToken().trim());
            jsonObject.put("androidId", AnalyticsUtil_pudamoney.INSTANCE.getAndroidId());
            jsonObject.put("userId", UserInfoHelper_pudamoney.getInstance().getUserId().trim());
            jsonObject.put("advertId", AnalyticsUtil_pudamoney.INSTANCE.getAdId());
            jsonObject.put("product", Constant_pudamoney.PRODUCT.trim());
            jsonObject.put("clientType", Constant_pudamoney.CLIENT.trim());
            jsonObject.put("apiVersion", "v3");
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //发送请求
    private void request(String lastWord, String jsonString) {
        requestWithoutCountryPrefix(Url_pudamoney.PATH_GLOBAL + lastWord,jsonString);
    }

    //发送请求（不带国家前缀）
    private void requestWithoutCountryPrefix(String lastWord, String jsonString) {

        ThreadUtil_pudamoney.getInstance().runOnUiThread(() -> HttpPresenter_pudamoney.getInstance().progressBarDialogShow());

        ThreadUtil_pudamoney.getInstance().runOnChildThread(() -> {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            Request request = new Request.Builder()
                    .url(Url_pudamoney.Url_base + lastWord)
                    .post(RequestBody.Companion.create(jsonString, mediaType))
                    .build();
            Call call = mClient.newCall(request);
            call.enqueue(callback);
        });
    }

    /**
     * 保存gp 安装渠道信息
     */
    public void saveGpInstallReferrerInfo(String installReferrer) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = getRequestJson();
                jsonObject.put("sourceType", "google");
                jsonObject.put("channelCode", installReferrer.trim());
                jsonObject.put("subChannelCode", installReferrer.trim());

                final String gurl = Url_pudamoney.Url_base + Url_pudamoney.PATH_GP_INSTALL_TEMP;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 保存af 安装渠道信息
     */
    public void saveAFInstallReferrerInfo(String installReferrer) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = getRequestJson();
                jsonObject.put("sessionData", installReferrer.trim());
                jsonObject.put("deviceId", AnalyticsUtil_pudamoney.INSTANCE.getAndroidId());

                final String gurl = Url_pudamoney.Url_base + Url_pudamoney.PATH_AF_INSTALL_TEMP;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 保存af 服务器回传信息
     */
    public void saveAFS2SEventInfo(String jsonString) {
        new Thread(() -> {
            try {
                final String gurl = Url_pudamoney.Url_base + Url_pudamoney.PATH_AF_INSTALL_S2S;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonString))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

//    //检查更新
//    public void queryAppVersion() {
//        request("/"+Country_Word+Url.PATH_APP_VERSION, getRequestJson().toString());
//    }

    //获取App配置
    public void getAppShowInfo() {
        request(Url_pudamoney.PATH_APP_SHOW_INFO, getRequestJson().toString());
    }

    //获取登录验证码
    public void requestOtpCode(String phoneNum) {
        UserInfoHelper_pudamoney.getInstance().setMobile(StringUtil_pudamoney.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            //jsonObject.put("channelCode", GPInstallHelper.getInstance().getInstallReferrer().trim());
            //jsonObject.put("subChannelCode", GPInstallHelper.getInstance().getInstallReferrer().trim());
            //jsonObject.put("code", "");
            jsonObject.put("mobile", phoneNum.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_pudamoney.PATH_SMS_CODE, jsonObject.toString());
    }

    //注册登录-有验证码
    public void userLogin(String phoneNum, String verCode) {
        UserInfoHelper_pudamoney.getInstance().setMobile(StringUtil_pudamoney.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_pudamoney.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_pudamoney.INSTANCE.getInstallReferrer());
            jsonObject.put("code", verCode.trim());
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("notBindWalletFlag", "YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_pudamoney.PATH_USER_LOGIN, jsonObject.toString());
    }

    //注册登录-老用户
    public void userLoginOldUser(String phoneNum) {
        UserInfoHelper_pudamoney.getInstance().setMobile(StringUtil_pudamoney.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_pudamoney.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_pudamoney.INSTANCE.getInstallReferrer());
            jsonObject.put("code", "0000");
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("directLoginFlag","YES");
            jsonObject.put("notBindWalletFlag","YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_pudamoney.PATH_USER_LOGIN, jsonObject.toString());
    }

    public void submitServiceFeedback(String type, String opinion) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type", type);
            jsonObject.put("opinion", opinion);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_pudamoney.PATH_FEED_BACK, jsonObject.toString());
    }

    //获取银行列表（尼日）
    public void fetchBankCodes_Niri() {
        request(Url_pudamoney.PATH_FETCH_BANK_CODE, getRequestJson().toString());
    }

    //请求用户流程状态
    public void requestUserProcess() {
        request(Url_pudamoney.PATH_USER_PROCESS, getRequestJson().toString());
    }

    //上传用户信息
    public void uploadInfo(String url, TreeMap<String, String> dataMap) {
        try {
            JSONObject jsonObject = getRequestJson();
            for (String k : dataMap.keySet()) {
                String key = StringUtil_pudamoney.getSafeString(k);
                String value = StringUtil_pudamoney.getSafeString(dataMap.get(k));
                jsonObject.put(key, value);
            }
            Upload_Info_Url = url;
            String prefix = Url_pudamoney.PATH_GLOBAL;
            if (!url.startsWith(prefix)) url = prefix + url;
            requestWithoutCountryPrefix(url, jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //请求额度列表
    public void queryLoanLimit() {
        request(Url_pudamoney.PATH_LOAN_LIMIT, getRequestJson().toString());
    }

    //请求借款申请页信息/贷款详情
    public void requestLoanApplyDetail() {
        request(Url_pudamoney.PATH_GET_LOAN_APPLY_DETAIL, getRequestJson().toString());
    }

    //发起借款申请
    public void loanApply() {
        request(Url_pudamoney.PATH_LOAN_APPLY, getRequestJson().toString());
    }

    //获取还款信息
    public void getRepayDetail() {
        request(Url_pudamoney.PATH_REPAY_INFO, getRequestJson().toString());
    }

    //初始化paystack订单（尼日）
    public void orderRepaySDK(String cardNumber, String expiryYear, String expiryMonth, String cvv) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cardNumber", cardNumber.trim());
            jsonObject.put("expiryYear", expiryYear.trim());
            jsonObject.put("expiryMonth", expiryMonth.trim());
            jsonObject.put("cvv", cvv.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_pudamoney.PATH_ORDER_REPAY_SDK, getRequestJson(jsonObject).toString());
    }

    //获取paystack卡列表（尼日）
    public void bankList_niri() {
        request(Url_pudamoney.PATH_BANK_LIST, getRequestJson().toString());
    }

    //线下还款-创建虚拟账号还款
    public void createVirtualAccount() {
        request(Url_pudamoney.PATH_CREATE_VIRTUAL_ACCOUNT, getRequestJson().toString());
    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = getRequestJson();
                jsonObject.put("type", Constant_pudamoney.PRODUCT +"_"+pageEvent);

                final String gurl = Url_pudamoney.Url_base + Url_pudamoney.PATH_GLOBAL + Url_pudamoney.PATH_USER_BURIED_POINT;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 保存firebase s2s需要信息
     */
    public void saveFirebaseS2SInfo() {
        new Thread(() -> {
            try {
                String gversion = BaseApplication_pudamoney.getApplication_pudamoney()
                        .getPackageManager()
                        .getPackageInfo(BaseApplication_pudamoney.getApplication_pudamoney().getPackageName(), PackageManager.GET_META_DATA)
                        .versionName;

                JSONObject jsonObject = getRequestJson();
                jsonObject.put("name", Constant_pudamoney.NAME);
                jsonObject.put("OSAndVersion", ("Android " + Build.VERSION.RELEASE));
                jsonObject.put("locale", Locale.getDefault().toString());
                jsonObject.put("device", Build.MODEL);
                jsonObject.put("appVersion", gversion);
                jsonObject.put("sdkVersion", gversion);
                jsonObject.put("build", "Build/" + Build.ID);
                jsonObject.put("lat", AnalyticsUtil_pudamoney.INSTANCE.getAdEnabled() + "");
//                jsonObject.put("firebaseAppId", FirebaseHelper.FIREBASE_APPID);
//                jsonObject.put("ga4AppInstanceId", FirebaseHelper.GA4_APP_INSTANCE_ID);

                final String gurl = Url_pudamoney.Url_base + Url_pudamoney.PATH_FIREBASE_S2S;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 上传图片
     */
    public void uploadImage(String filePath_equitable) {
        if (Looper.myLooper()!=Looper.getMainLooper())
            ThreadUtil_pudamoney.getInstance().runOnUiThread(() -> HttpPresenter_pudamoney.getInstance().progressBarDialogShow());
        else HttpPresenter_pudamoney.getInstance().progressBarDialogShow();
        try {
            if (!TextUtils.isEmpty(filePath_equitable)) {
                String fileSuffix_equitable = filePath_equitable.endsWith(".png") ? "image/png" : "image/jpg";
                final MediaType mediaType_equitable = MediaType.parse(fileSuffix_equitable);
                final File imageFile_equitable = new File(filePath_equitable);
                final String uplodUrl_equitable = Url_pudamoney.Url_base+ Url_pudamoney.PATH_GLOBAL + Url_pudamoney.PATH_UPLOAD_IMAGE_FILE;

                if (imageFile_equitable.isFile()) {
                    RequestBody imageBody = RequestBody.create(mediaType_equitable, imageFile_equitable);

                    RequestBody requestBody_equitable = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("image", imageFile_equitable.getName(), imageBody)
                            .build();

                    Request request_equitable = new Request.Builder()
                            .url(uplodUrl_equitable)
                            .post(requestBody_equitable)
                            .build();

                    Call call = mClient.newCall(request_equitable);
                    call.enqueue(callback);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
